<template>
  <!-- el-card 卡片  shadow 具有移入效果 -->
  <el-card shadow="hover" v-loading="loading">
    <!-- 设置头部分割线 -->
    <template #header>
      <!-- el-button 按钮  type=按钮颜色  ：icon 添加图标  要引入 -->
      <el-button type="primary" :icon="Plus" @click="addOrUpdateTradeMark()"
        >添加</el-button
      >
    </template>
    <!-- 表格  border--边框   data 数据表-->
    <el-table border :data="trademarkListData">
      <!-- column-列  props--该列所展示的数据  width-- 设置宽度  align 文本居中  -->
      <el-table-column label="序号" width="80px" align="center" type="index" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <!-- 自定义列的内容 作用域参数为 { row(行), column（列）, $index（索引） } -->
        <template v-slot="{ row }">
          <img :src="row.logoUrl" class="logoUrlSize" />
        </template>
      </el-table-column>

      <el-table-column prop="date" label="操作">
        <template #default="{ row }">
          <el-button
            type="warning"
            :icon="Edit"
            @click="addOrUpdateTradeMark(row)"
          ></el-button>
          <el-button
            type="danger"
            :icon="Delete"
            @click="deleteTrademark(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="spaceArea"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9]"
      layout=" prev, pager, next, jumper ,->,sizes,total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- dialog 添加对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`${ruleForm.id > 0 ? '修改' : '添加'}品牌`"
    >
      <el-form :rules="rules" :model="ruleForm" ref="ruleFormRef">
        <el-form-item label="名牌名称" prop="tmName">
          <el-input v-model="ruleForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- 上传图片 ,upload组件-->
          <el-upload
            class="avatar-uploader"
            :action="appDev"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="ruleForm.logoUrl"
              :src="ruleForm.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip text-red">
                只能上传jpg/png文件，且不超过50kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmItem(ruleFormRef)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
//给组件定义配置，定义组件名
defineOptions({
  name: "trademark",
});
//从element-plus 引入所需的图标
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  reqGetTradeMarkList,
  reqAddTradeMark,
  reqEditTradeMark,
  reqDeleteTradeMark,
} from "@/api/product/trademark.ts";
import type {
  TrademarkList,
  TrademarkItem,
} from "@/api/product/models/trademarkType.ts";
import { ref, onMounted, reactive } from "vue";
import type { FormInstance } from "element-plus";
//3、删除单项名牌
const deleteTrademark = (row: TrademarkItem) => {
  ElMessageBox.confirm(`确定要删除${row.tmName}品牌嘛？`, "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      //发送删除请求
      await reqDeleteTradeMark(row.id);
      getTradeMarkListApi();
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete canceled",
      });
    });
};

//2、添加和编辑品牌功能
interface RuleForm {
  id: number;
  tmName: string;
  logoUrl: string;
}
//获取表单数据
const ruleForm = reactive<RuleForm>({
  id: 0,
  tmName: "",
  logoUrl: "",
});
//品牌必填校验
const rules = ref({
  tmName: [
    {
      required: true,
      message: "请输入品牌名称",
      trigger: "blur",
    },
    { min: 5, max: 20, message: "名牌名称5-20字", trigger: "blur" },
  ],
  logoUrl: [
    {
      required: true,
      message: "请上传品牌图片",
    },
  ],
});
//控制对话框显示和隐藏
const dialogVisible = ref(false);
//获取代理地址
const BASE_URL = import.meta.env.VITE_API_URL;
const appDev = `${BASE_URL}/admin/product/fileUpload`;

//点击添加和编辑按钮操作，显示对话框，添加数据‘
const addOrUpdateTradeMark = (
  //没传数据就显示默认值
  row: TrademarkItem = { id: 0, tmName: "", logoUrl: "" }
) => {
  dialogVisible.value = true;
  ruleForm.tmName = row.tmName;
  ruleForm.logoUrl = row.logoUrl;
  ruleForm.id = row.id;
  //清理某个字段的表单验证信息。不写参数就是清除所有校验信息
  //挂载时对话框不显示，此时实例为undefined
  ruleFormRef.value?.clearValidate();
};

//上传图片
import type { UploadProps } from "element-plus";

//图片提交成功触发色回调函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  //获取上传图片地址
  ruleForm.logoUrl = response.data;
};
//图片上传之前的回调函数，校验图片大小
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgType = ["image/jpeg", "image/jpg", "image/png"];
  if (!imgType.includes(rawFile.type)) {
    ElMessage.error("图片支持jpeg,jpg,png 格式");
    return false; //格式错误就不上传
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error("图片超过50Mb!");
    return false;
  }
  return true; //图片符合需求就上传
};

//获取真实DOM
const ruleFormRef = ref();
//点击确认按钮，添加数据，页面重新渲染
const confirmItem = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  const trademark = {
    id: ruleForm.id,
    tmName: ruleForm.tmName,
    logoUrl: ruleForm.logoUrl,
  };
  try {
    //validate，任一表单项触发校验功能
    await formEl.validate();
    //校验成功后发送添加请求,通过id判断是发送添加需求还是修改
    if (ruleForm.id > 0) {
      await reqEditTradeMark(trademark);
      // console.log(111);
    } else {
      await reqAddTradeMark(ruleForm.tmName, ruleForm.logoUrl);
    }

    getTradeMarkListApi();
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error("请填写品牌内容");
  }
};

//1、分页器获取数据
const currentPage = ref(1); //当前页
const pageSize = ref(3); //每页条数
const total = ref(0); //总数
//自定义指令 加载效果，通过开关变量来控制
const loading = ref(false);
// 每页条数发生变化时触发
const handleSizeChange = () => {
  //切换一页多少条 发送请求数据
  getTradeMarkListApi();
};
//当前页发生改变触发
const handleCurrentChange = () => {
  //当点击分页器当前页获取最新数据
  getTradeMarkListApi();
};

//封装获取品牌数据列表
const getTradeMarkListApi = async () => {
  //每次发请求前，开启加载效果
  loading.value = true;
  const result = await reqGetTradeMarkList(currentPage.value, pageSize.value);
  // console.log(result);  //总数据
  trademarkListData.value = result.records;
  total.value = result.total;
  currentPage.value = result.current;
  //每次发请求完，关闭加载效果
  loading.value = false;
};

const trademarkListData = ref<TrademarkList>([]);
//挂载阶段发送请求获取数据
onMounted(getTradeMarkListApi);
</script>

<style scoped lang="scss">
.spaceArea {
  margin: 20px 0;
}
.logoUrlSize {
  width: 100px;
  height: 100px;
}

.avatar-uploader {
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  :deep() {
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
@/Api/product/models/TrademarkType @/Api/product/models/TrademarkTypexxx
@/api/product/models/trademarkType @/api/product/models/TrademarkType
@/api/product/models/trademarkType
